<template>
  <div class="found" ref="foundRef">
    <div class="header app-header">
      <van-search
        placeholder="请输入搜索关键词"
        input-align="center"
        shape="round"
        disabled
        @click="onSearch"
      />
    </div>
    <van-tabs
      v-model:active="tabActive"
      sticky
      offset-top="14.3vw"
      color="#1c8cfc"
      class="tabs"
      @change="onChangeTab"
      :before-change="onBeforeChangeTab"
      animated
      swipeable
    >
      <template v-for="item in tags" :key="item.id">
        <van-tab :title="item.name" :name="item.id">
          <article-list
            :tag-id="item.id"
            :method="'tag'"
            :is-immediate="true"
          />
        </van-tab>
      </template>
    </van-tabs>
    <van-button
      icon="back-top"
      round
      class="backBtn"
      v-if="y >= 300"
      @click="onBackTop"
    />
  </div>
</template>

<script setup lang="ts">
import { useScroll } from '@vueuse/core'
import ArticleList from '../../../components/article-list.vue'
import { getTags } from '../../../service/tag'
import { tagsRes } from '../../../service/tag/types'

interface scrollPos {
  id: number
  position: number
}

const router = useRouter()
const tabActive = ref<number>(0)
const tags = ref<tagsRes.Tag[]>([])
const foundRef = ref<HTMLElement | null>(null)
const scrollPosition = reactive<scrollPos[]>([])
const { y } = useScroll(foundRef)

const onSearch = () => {
  router.push('/search')
}
const onBackTop = () => {
  foundRef.value?.scrollTo(0, 0)
}
const onBeforeChangeTab = () => {
  const beforeTab = scrollPosition.find((item) => item.id === tabActive.value)
  if (beforeTab?.id) beforeTab['position'] = y.value
  return true
}
const onChangeTab = () => {
  const scroll = scrollPosition.find((item) => item.id === tabActive.value)
  if (scroll?.id) {
    setTimeout(() => {
      if (foundRef.value) foundRef.value.scrollTop = scroll.position
    }, 5)
  }
}
const loadTags = async () => {
  const res = await getTags()
  tags.value.push(...res.data.tags)
  tags.value.unshift({
    id: -1,
    name: '最新发布',
    createTime: new Date(),
    updateTime: new Date()
  })
  tags.value.forEach((item) => {
    scrollPosition.push({
      id: item.id,
      position: 0
    })
  })
}

onMounted(() => {
  loadTags()
})
onActivated(() => {
  if (!foundRef.value) return
  foundRef.value.scrollTop = y.value
})
</script>

<style lang="scss" scoped>
.found {
  .tabs {
    padding-top: 54px;
    :deep(.van-tabs__content) {
      height: calc(100% - 44px);
      .van-tab__panel {
        height: 100%;
      }
    }
  }
  .backBtn {
    height: 44px;
    width: 44px;
    position: fixed;
    bottom: 100px;
    right: 10px;
    z-index: 99;
  }
}
</style>
